package cc.zzone.util;

import org.brotli.dec.BrotliInputStream;
import org.springframework.util.FileCopyUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * 数据解压缩 工具类
 *
 * @author jinzhengze
 * @since 2023年10月10日
 */
public final class DecodeUtil {

    private DecodeUtil() {
    }

    /**
     * 压缩
     */
    public static byte[] compress(byte[] data) {
        byte[] output;
        Deflater compressor = new Deflater();
        compressor.reset();
        compressor.setInput(data);
        compressor.finish();
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length)) {
            byte[] buf = new byte[1024];
            while (!compressor.finished()) {
                int i = compressor.deflate(buf);
                bos.write(buf, 0, i);
            }
            output = bos.toByteArray();
        } catch (Exception e) {
            output = data;
        }
        compressor.end();
        return output;
    }

    /**
     * 解压缩
     */
    public static byte[] decompress(byte[] data) {
        byte[] output;
        Inflater decompressor = new Inflater();
        decompressor.reset();
        decompressor.setInput(data);

        try (ByteArrayOutputStream o = new ByteArrayOutputStream(data.length)) {
            byte[] buf = new byte[1024];
            while (!decompressor.finished()) {
                int i = decompressor.inflate(buf);
                o.write(buf, 0, i);
            }
            output = o.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            output = data;
        }
        decompressor.end();
        return output;
    }

    /**
     * Brotli 解压缩
     */
    public static byte[] brotliDecompress(byte[] data) {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream(data.length)) {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
            BrotliInputStream in = new BrotliInputStream(byteArrayInputStream);
            FileCopyUtils.copy(in, out);
            return out.toByteArray();
        } catch (Exception ignored) {
            return data;
        }
    }
}
